/*
 * @Date         : 2020-01-12 22:55:58
 * @LastEditors  : Mao NianYou
 * @LastEditTime : 2020-01-12 23:41:41
 */
(function() {
    // 按照概率获取所中奖项
    let luckyDraw = function (rates) {
        const hit = Math.random() * 100

        let finder = rates.find(item=>{
            return hit >= item.range.x && hit < item.range.y
        })

        console.log(`概率范围: ${hit} | 所中奖项: ${finder.id}`)
        return finder.id
    }

    // 把中奖项目调整为指定项目
    // i: 所中奖项的index
    let cheetToReward = function (moveCount, i) {
        while (moveCount % _awardsCount !== i) {
            moveCount += 1
        }
        return moveCount
    }

    // 获取本次滚动的随机次数
    let getMoveCount = function (hit, max = 60) {
        let moveCount = Math.ceil(Math.random() * max)
        if (moveCount < minMove) {
            moveCount += minMove
        }

        // 根据抽中奖项调整随机滚动次数
        moveCount = cheetToReward(moveCount, hit)
        
        return moveCount
    }

    let _awardsCount = 0

    function _lottery(rates) {
        _awardsCount = rates.length
        console.log(`rates: [${rates}]`)

        let temp = 0
        const _rates = rates.map((rate, index)=>{
            temp += rate
            return {
                id: index,
                range: {
                    x: temp - rate,
                    y: temp
                }
            }
        })

        const lucky = luckyDraw(_rates)
        const moveCount = getMoveCount(lucky)

        return moveCount
    }

    window.lottery = _lottery
})()